<template>
  <Pie class="w-full" ref="pieChartRef" :data="chartData" :options="options" />
</template>
<script lang="ts" setup>
import { ref, computed, watch } from "vue";
import { Pie } from "vue-chartjs";
import {
  Chart,
  ArcElement,
  PieController,
  Legend,
  Title,
  Tooltip,
  ChartData,
  ChartOptions,
} from "chart.js";
import { useTodosStore } from "@/stores/todos";
import { breakpoints } from "./config";
// chart register
Chart.register(PieController, ArcElement, Legend, Title, Tooltip);

const todosStore = useTodosStore();
const greaterLg = breakpoints.greater("lg");

// options
const options = computed<ChartOptions<"pie">>(() => ({
  responsive: true,
  resizeDelay: 250,
  layout: {
    padding: 10,
  },
  plugins: {
    legend: {
      display: true,
      position: greaterLg.value ? "right" : "bottom",
      align: greaterLg.value ? "center" : "start",
      labels: {
        boxWidth: 15,
        font: {
          size: greaterLg.value ? 12 : 8,
        },
      },
    },
    title: {
      display: true,
      text: "待办完成情况",
      font: {
        size: greaterLg.value ? 16 : 12,
        weight: "bolder",
      },
    },
  },
}));
// const priority = ["Normal", "Important", "Crucial"];
const chartData = computed<ChartData<"pie">>(() => {
  const data: number[] = [];
  for (let item of [todosStore.stat.finished, todosStore.stat.notFinish])
    data.push(item.Normal || 0, item.Important || 0, item.Crucial || 0);
  return {
    // labels: ["F & N", "F & I", "F & C", "N & N", "N & I", "N & C"],
    labels: [
      "完成&一般",
      "完成&重要",
      "完成&至关重要",
      "未完成&一般",
      "未完成&重要",
      "未完成&至关重要",
    ],
    datasets: [
      {
        data,
        backgroundColor: [
          "#d9f99d",
          "#a3e635",
          "#65a30d",
          "#fbcfe8",
          "#f472b6",
          "#db2777",
        ],
        borderWidth: 2,
      },
    ],
  };
});
const pieChartRef = ref<typeof Pie>();
const resize = () => pieChartRef.value?.chart?.resize(),
  toBase64Image = () => pieChartRef.value?.chart?.toBase64Image();
// 定义组件导出
defineExpose({
  toBase64Image,
});

watch(greaterLg, () => {
  // console.log(pieChartRef.value?.chartInstance);
  resize();
});
</script>
